home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / clang / mempool.zip / LINK.H next >
C/C++ Source or Header  |  1994-02-10  |  2KB  |  101 lines

  1. #include "mempool.h"
  2. #include <fstream.h>
  3. #include <string.h>
  4.               
  5. class Link {
  6.   char *data;
  7.   Link *next;
  8.   static MemoryPool pool;
  9. public:
  10.   friend class List;
  11.   friend class Iterator;
  12.   Link(const char *_data, 
  13.     Link *_next) 
  14.   { 
  15.     next = _next; 
  16.     data = strcpy(new 
  17.       char[strlen(_data)+1],
  18.       _data); 
  19.   }
  20.   ~Link() 
  21.   { 
  22.     delete data; 
  23.   }
  24.   void *
  25.     operator new(size_t) 
  26.   { 
  27.     return pool.malloc(); 
  28.   }
  29.   void 
  30.     operator delete(void *ptr) 
  31.   { 
  32.     pool.free(ptr); 
  33.   }
  34. };
  35.               
  36. MemoryPool 
  37. Link::pool(sizeof(Link));
  38.               
  39. class List {
  40.   Link head;
  41. public:
  42.   friend class Iterator;
  43.   List ();
  44.   ~List();
  45.   void add(char *data);
  46. };
  47.               
  48. class Iterator {
  49.   Link *link;
  50. public:
  51.   Iterator(List &_list) 
  52.   { 
  53.     link = _list.head.next; 
  54.   }
  55.   char *Next() 
  56.   { 
  57.     char *ret = link ? 
  58.       link->data : NULL; 
  59.     link = link->next; 
  60.     return ret;
  61.   }
  62. };
  63.               
  64. List::List()
  65.   : head("",NULL)
  66. {
  67.   ;
  68. }
  69.               
  70. List::~List()
  71. {
  72.   while(head.next)
  73.   {
  74.     Link *temp = 
  75.       head.next->next;
  76.     delete head.next;
  77.     head.next = temp;
  78.   }
  79. }
  80.  
  81. void List::add(char *data)
  82. {
  83.   head.next = new 
  84.     Link(data,head.next);
  85. }
  86.               
  87. main(int, char **argv)
  88. {
  89. static char buff[1024];
  90.   List list;
  91.   ifstream in(argv[1]);
  92.   while(in.getline(buff,
  93.     sizeof(buff)))
  94.     list.add(buff);
  95.   Iterator it(list);
  96.   char *ptr;
  97.   while((ptr = it.Next()) != 
  98.     NULL)
  99.     cout << ptr << endl;
  100. }
  101.